import { useState, forwardRef, useImperativeHandle, useRef, useEffect } from 'react';
import { Task, Category, TaskFormData, CategoryFormData } from './types';
import { useNavigate } from 'react-router-dom';
import { Modal } from './Modal';
import ConfirmDialog from '../PopupBox/ConfirmDialog';

interface TaskListProps {
  tasks: Task[];
  categories: Category[];
  dispatch: (action: any) => void;
}

export interface TaskListHandle {
  handleOpenTaskModal: () => void;
  handleOpenCategoryModal: () => void;
}

export const TaskList = forwardRef<TaskListHandle, TaskListProps>(({ tasks, categories, dispatch }, ref) => {
  const navigate = useNavigate();
  const [isTaskModalOpen, setIsTaskModalOpen] = useState(false);
  const [isCategoryModalOpen, setIsCategoryModalOpen] = useState(false);
  const [currentTask, setCurrentTask] = useState<Task | null>(null);
  const [currentCategory, setCurrentCategory] = useState<Category | null>(null);
  const [taskForm, setTaskForm] = useState<TaskFormData>({
    taskTitle: '',
    taskGuide: '',
    category: categories.length > 0 ? categories[0].name : ''
  });
  const [categoryForm, setCategoryForm] = useState<CategoryFormData>({
    name: ''
  });
  const [openMenuId, setOpenMenuId] = useState<string | null>(null);
  const menuRefs = useRef<{ [key: string]: HTMLDivElement | null }>({});
  const [confirmDialogOpen, setConfirmDialogOpen] = useState(false);
  const [confirmDialogAction, setConfirmDialogAction] = useState<() => void>(() => {});
  const [confirmDialogTitle, setConfirmDialogTitle] = useState('');
  const [confirmDialogContent, setConfirmDialogContent] = useState('');
  
  // 处理点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (openMenuId && menuRefs.current[openMenuId] && 
          !menuRefs.current[openMenuId]?.contains(event.target as Node)) {
        setOpenMenuId(null);
      }
    };
    
    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [openMenuId]);
  
  // 保存菜单引用的回调函数
  const setMenuRef = (element: HTMLDivElement | null, taskId: string) => {
    menuRefs.current[taskId] = element;
  };
  
  // 暴露方法给父组件
  useImperativeHandle(ref, () => ({
    handleOpenTaskModal: () => {
      setCurrentTask(null);
      setTaskForm({
        taskTitle: '',
        taskGuide: '',
        category: categories.length > 0 ? categories[0].name : ''
      });
      setIsTaskModalOpen(true);
    },
    handleOpenCategoryModal: () => {
      setCurrentCategory(null);
      setCategoryForm({
        name: ''
      });
      setIsCategoryModalOpen(true);
    }
  }));
  
  // 任务表单处理
  const handleOpenTaskModal = (task?: Task) => {
    if (task) {
      setCurrentTask(task);
      setTaskForm({
        taskTitle: task.taskTitle,
        taskGuide: task.taskGuide,
        category: task.category
      });
    } else {
      setCurrentTask(null);
      setTaskForm({
        taskTitle: '',
        taskGuide: '',
        category: categories.length > 0 ? categories[0].name : ''
      });
    }
    setIsTaskModalOpen(true);
  };

  const handleTaskSubmit = () => {
    if (currentTask) {
      // 更新任务
      dispatch({
        type: 'UPDATE_TASK',
        payload: {
          ...currentTask,
          taskTitle: taskForm.taskTitle,
          taskGuide: taskForm.taskGuide,
          category: taskForm.category
        }
      });
    } else {
      // 创建新任务
      const taskId = Date.now().toString();
      dispatch({
        type: 'ADD_TASK',
        payload: {
          id: taskId,
          taskId: taskId,
          taskTitle: taskForm.taskTitle,
          taskGuide: taskForm.taskGuide,
          category: taskForm.category,
          status: 'success',
          duration: '0秒',
          createdAt: new Date(),
          logs: []
        }
      });
    }
    setIsTaskModalOpen(false);
  };

  const handleDuplicateTask = (task: Task) => {
    const newTaskId = Date.now().toString();
    const newTask = {
      ...task,
      id: newTaskId,
      taskId: newTaskId,
      taskTitle: `${task.taskTitle} (复制)`,
      createdAt: new Date()
    };
    dispatch({
      type: 'ADD_TASK',
      payload: newTask
    });
    setOpenMenuId(null);
  };

  const handleDeleteTask = (id: string) => {
    setConfirmDialogTitle('确认删除');
    setConfirmDialogContent('确定要删除此任务吗？');
    setConfirmDialogAction(() => () => {
      dispatch({
        type: 'DELETE_TASK',
        id
      });
      setOpenMenuId(null);
    });
    setConfirmDialogOpen(true);
  };

  const handleRunTask = (task: Task) => {
    setConfirmDialogTitle('确认运行');
    setConfirmDialogContent('确定要运行此任务吗？');
    setConfirmDialogAction(() => () => {
      navigate('/execution', { 
        state: { 
          selectedTaskIds: [task.id],
          fromPage: '任务库'
        } 
      });
    });
    setConfirmDialogOpen(true);
  };

  const handleCategorySubmit = () => {
    if (currentCategory) {
      // 更新分类
      dispatch({
        type: 'UPDATE_CATEGORY',
        payload: {
          ...currentCategory,
          name: categoryForm.name
        }
      });
    } else {
      // 创建新分类
      dispatch({
        type: 'ADD_CATEGORY',
        payload: {
          id: Date.now().toString(),
          name: categoryForm.name
        }
      });
    }
    setIsCategoryModalOpen(false);
  };

  // 切换菜单显示状态
  const toggleMenu = (taskId: string) => {
    setOpenMenuId(openMenuId === taskId ? null : taskId);
  };

  return (
    <div>
      {/* 操作按钮 */}
      <div className="flex flex-wrap justify-between items-center mb-6">
        <h2 className="text-xl font-semibold">任务列表</h2>
        <div className="space-x-2 flex">
          <button
            className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            onClick={() => handleOpenTaskModal()}
          >
            创建任务
          </button>
        </div>
      </div>


      {/* 任务列表 */}
      {tasks.length === 0 ? (
        <div className="p-8 text-center text-gray-500 bg-white rounded-lg shadow">
          没有找到任务。创建新任务或调整筛选条件。
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          {tasks.map(task => (
            <div key={task.id} className="bg-white rounded-lg shadow overflow-hidden">
              <div className="p-4">
                <div className="font-medium text-lg mb-2">{task.taskTitle}</div>
                <p className="text-gray-600 mb-3 line-clamp-2">{task.taskGuide}</p>
                <div className="flex flex-wrap gap-2 mb-3">
                  <span className="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-800 font-medium">
                    {task.category}
                  </span>
                </div>
              </div>
              <div className="bg-gray-50 px-4 py-3 flex justify-between items-center">
                <div className="text-xs text-gray-500">
                  {new Date(task.createdAt).toLocaleDateString()}
                </div>
                <div className="flex space-x-2">
                  <button 
                    className="p-1 rounded-full hover:bg-gray-200 text-gray-600"
                    title="运行任务"
                    onClick={() => handleRunTask(task)}
                  >
                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                  </button>
                  <div className="relative">
                    <button 
                      className="p-1 rounded-full hover:bg-gray-200 text-gray-600"
                      title="更多操作"
                      onClick={() => toggleMenu(task.id)}
                    >
                      <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h.01M12 12h.01M19 12h.01M6 12a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0zm7 0a1 1 0 11-2 0 1 1 0 012 0z" />
                      </svg>
                    </button>
                    {openMenuId === task.id && (
                      <div 
                        ref={(el) => setMenuRef(el, task.id)}
                        className="absolute right-0 bottom-full mb-1 w-40 bg-white rounded-md shadow-lg overflow-hidden z-50"
                      >
                        <div className="py-1">
                          <button
                            className="w-full px-4 py-2 text-sm text-left text-gray-700 hover:bg-gray-100"
                            onClick={() => handleOpenTaskModal(task)}
                          >
                            编辑
                          </button>
                          <button
                            className="w-full px-4 py-2 text-sm text-left text-gray-700 hover:bg-gray-100"
                            onClick={() => handleDuplicateTask(task)}
                          >
                            复制
                          </button>
                          <button
                            className="w-full px-4 py-2 text-sm text-left text-gray-700 hover:bg-gray-100"
                            onClick={() => handleDeleteTask(task.id)}
                          >
                            删除
                          </button>
                        </div>
                      </div>
                    )}
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* 任务表单模态框 */}
      <Modal
        isOpen={isTaskModalOpen}
        onClose={() => setIsTaskModalOpen(false)}
        title={currentTask ? "编辑任务" : "创建任务"}
      >
        <form onSubmit={(e) => { e.preventDefault(); handleTaskSubmit(); }}>
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              标题
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={taskForm.taskTitle}
              onChange={(e) => setTaskForm({...taskForm, taskTitle: e.target.value})}
              required
            />
          </div>
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              描述
            </label>
            <textarea
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              rows={3}
              value={taskForm.taskGuide}
              onChange={(e) => setTaskForm({...taskForm, taskGuide: e.target.value})}
              required
            />
          </div>
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              分类
            </label>
            <select
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={taskForm.category}
              onChange={(e) => setTaskForm({...taskForm, category: e.target.value})}
              required
            >
              {categories.map((category) => (
                <option key={category.id} value={category.name}>
                  {category.name}
                </option>
              ))}
            </select>
          </div>
          <div className="flex justify-end space-x-2">
            <button
              type="button"
              className="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500"
              onClick={() => setIsTaskModalOpen(false)}
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              保存
            </button>
          </div>
        </form>
      </Modal>

      {/* 分类表单模态框 */}
      <Modal
        isOpen={isCategoryModalOpen}
        onClose={() => setIsCategoryModalOpen(false)}
        title={currentCategory ? "编辑分类" : "创建分类"}
      >
        <form onSubmit={(e) => { e.preventDefault(); handleCategorySubmit(); }}>
          <div className="mb-4">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              分类名称
            </label>
            <input
              type="text"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
              value={categoryForm.name}
              onChange={(e) => setCategoryForm({...categoryForm, name: e.target.value})}
              required
            />
          </div>
          <div className="flex justify-end space-x-2">
            <button
              type="button"
              className="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500"
              onClick={() => setIsCategoryModalOpen(false)}
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              保存
            </button>
          </div>
        </form>
      </Modal>

      {/* 确认对话框 */}
      <ConfirmDialog
        open={confirmDialogOpen}
        title={confirmDialogTitle}
        content={confirmDialogContent}
        onConfirm={() => {
          confirmDialogAction();
          setConfirmDialogOpen(false);
        }}
        onCancel={() => setConfirmDialogOpen(false)}
      />
    </div>
  );
}); 

export default TaskList;